package com.pulse.base.mqtt;

import com.pulse.mqtt.MqttConsumer;
import com.pulse.mqtt.config.MqttConfiguration;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class MattServer implements ApplicationRunner {

    @Autowired
    private ApplicationContext context;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        MqttConsumer mqttConsumer = MqttConsumer.getSingleton();

        MqttConfiguration config = context.getBean(MqttConfiguration.class);

        // 添加主题配置基本信息
        mqttConsumer.setMqttConfiguration(config.getHost(),config.getClientId(),config.getUsername(),config.getPassword(),
                config.getTopic(),config.getQos(),config.getKeepalive(), config.getTimeout());

        mqttConsumer.mqttRun(args);

        // 设置主题消息回调
        MqttClient client = mqttConsumer.getMqttClient();
        mqttConsumer.create(createMqttCallBack(mqttConsumer,client,mqttConsumer.getMqttConfiguration()));
    }

    private MqttCallback createMqttCallBack(MqttConsumer mqttConsumer, MqttClient client, MqttConfiguration conf){
        String topic = null;
        MqttConnectOptions options = null;
        int[] qos = null;
        options = mqttConsumer.getOptions(conf);
        topic = conf.getTopic();
        qos = mqttConsumer.getQos(topic.split(",").length,conf.getQos());
        return new MqttCallback(client,options,topic.split(","),qos,client.getClientId());
    }
}
